<template>
  <view class="page">
    <!-- 收货地址 -->
    <view class="address-section" @click="selectAddress" :class="{ 'has-address': selectedAddress }">
      <view class="address-content" v-if="selectedAddress">
        <view class="address-header">
          <text class="receiver-name">{{ selectedAddress.contactName }}</text>
          <text class="receiver-phone">{{ selectedAddress.contactPhone }}</text>
          <text class="selected-badge">当前地址</text>
        </view>
        <view class="address-detail">
          <text class="address-icon">📍</text>
          <text class="address-text">{{ formatAddress(selectedAddress) }}</text>
        </view>
      </view>
      <view class="address-empty" v-else>
        <text class="empty-icon">📍</text>
        <text class="empty-text">请选择收货地址</text>
      </view>
      <text class="arrow-icon">›</text>
    </view>

    <!-- 商品列表 -->
    <view class="product-section">
      <view class="section-title">商品清单</view>
      <view class="product-item" v-for="(item, index) in orderItems" :key="index">
        <image 
          class="product-image" 
          :src="item.image || '/static/images/product-default.png'"
          mode="aspectFill"
        ></image>
        <view class="product-info">
          <text class="product-name">{{ item.name }}</text>
          <view class="product-footer">
            <text class="product-price">¥{{ item.price }}</text>
            <text class="product-quantity">x{{ item.quantity }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 配送方式 -->
    <view class="delivery-section">
      <view class="section-title">配送方式</view>
      <view class="delivery-item">
        <text class="delivery-icon">🚚</text>
        <text class="delivery-text">配送到宿舍</text>
        <text class="delivery-fee">+¥{{ deliveryFee }}</text>
      </view>
    </view>

    <!-- 订单备注 -->
    <view class="remark-section">
      <view class="section-title">订单备注</view>
      <textarea 
        class="remark-input" 
        v-model="remark"
        placeholder="选填，如特殊要求等"
        maxlength="200"
      ></textarea>
    </view>

    <!-- 起送提示 -->
    <view class="min-amount-tip" v-if="minOrderAmount > 0">
      <view class="tip-content" :class="{ reached: isMinAmountReached }">
        <text class="tip-icon">{{ isMinAmountReached ? '✅' : '⚠️' }}</text>
        <text class="tip-text" v-if="isMinAmountReached">
          已满足起送金额 ¥{{ minOrderAmount }}
        </text>
        <text class="tip-text" v-else>
          还差 ¥{{ remainingAmount }} 即可配送（起送 ¥{{ minOrderAmount }}）
        </text>
      </view>
    </view>

    <!-- 费用明细 -->
    <view class="fee-section">
      <view class="fee-item">
        <text class="fee-label">商品金额</text>
        <text class="fee-value">¥{{ totalAmount }}</text>
      </view>
      <view class="fee-item">
        <text class="fee-label">配送费</text>
        <text class="fee-value">+¥{{ deliveryFee }}</text>
      </view>
      <view class="fee-item total">
        <text class="fee-label">实付金额</text>
        <text class="fee-value highlight">¥{{ actualAmount }}</text>
      </view>
    </view>

    <!-- 底部提交栏 -->
    <view class="bottom-bar">
      <view class="bar-left">
        <text class="total-label">合计：</text>
        <text class="total-symbol">¥</text>
        <text class="total-value">{{ actualAmount }}</text>
      </view>
      <view 
        class="btn-submit" 
        :class="{ disabled: !isMinAmountReached }"
        @click="submitOrder"
      >
        <text class="btn-text" v-if="isMinAmountReached">提交订单</text>
        <text class="btn-text" v-else>还差¥{{ remainingAmount }}</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      fromPage: '', // 来源页面：cart 或 detail
      orderItems: [], // 订单商品
      selectedAddress: null, // 选中的地址
      remark: '', // 订单备注
      deliveryFee: 0, // 配送费（从系统配置获取）
      minOrderAmount: 0, // 起送金额（从系统配置获取）
      submitting: false
    }
  },
  computed: {
    // 商品总金额
    totalAmount() {
      return this.orderItems
        .reduce((sum, item) => sum + item.price * item.quantity, 0)
        .toFixed(2)
    },
    
    // 实付金额
    actualAmount() {
      return (parseFloat(this.totalAmount) + parseFloat(this.deliveryFee)).toFixed(2)
    },
    
    // 是否满足起送金额
    isMinAmountReached() {
      return parseFloat(this.totalAmount) >= parseFloat(this.minOrderAmount)
    },
    
    // 距离起送金额还差多少
    remainingAmount() {
      const remaining = parseFloat(this.minOrderAmount) - parseFloat(this.totalAmount)
      return remaining > 0 ? remaining.toFixed(2) : 0
    }
  },
  onLoad(options) {
    // 获取来源页面
    this.fromPage = options.from || ''
    
    // 获取订单商品
    if (options.items) {
      try {
        this.orderItems = JSON.parse(decodeURIComponent(options.items))
      } catch (error) {
        console.error('解析订单商品失败:', error)
        uni.showToast({ title: '订单数据错误', icon: 'none' })
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      }
    }
    
    // 加载默认地址
    this.loadDefaultAddress()
    
    // 加载配送费配置
    this.loadDeliveryFee()
  },
  onShow() {
    // 从地址选择页返回时，会更新selectedAddress
    // 在页面onShow时无需重新加载
  },
  methods: {
    // 格式化地址
    formatAddress(item) {
      let address = ''
      if (item.building) address += item.building
      if (item.room) address += (address ? '-' : '') + item.room
      if (item.detail) address += (address ? ' ' : '') + item.detail
      return address || '暂无详细地址'
    },

    async loadDeliveryFee() {
      try {
        const { getSnackConfigs } = require('@/api/config')
        const configs = await getSnackConfigs()
        
        if (configs) {
          this.deliveryFee = parseFloat(configs.deliveryFee) || 0
          this.minOrderAmount = parseFloat(configs.minOrderAmount) || 0
        }
      } catch (error) {
        console.error('加载配送费失败:', error)
        // 失败时使用默认值
        this.deliveryFee = 2
        this.minOrderAmount = 2
      }
    },
    
    async loadDefaultAddress() {
      try {
        const { getAddressList } = require('@/api/address')
        const list = await getAddressList()
        
        // 查找默认地址
        const defaultAddress = list.find(item => item.isDefault === 1)
        if (defaultAddress) {
          this.selectedAddress = defaultAddress
        } else if (list.length > 0) {
          // 没有默认地址，使用第一个
          this.selectedAddress = list[0]
        }
      } catch (error) {
        console.error('加载地址失败:', error)
      }
    },
    
    selectAddress() {
      uni.navigateTo({
        url: '/pages/address/list?select=true'
      })
    },
    
    async submitOrder() {
      // 防止重复提交
      if (this.submitting) return
      
      // 校验地址
      if (!this.selectedAddress) {
        uni.showToast({
          title: '请选择收货地址',
          icon: 'none'
        })
        return
      }
      
      // 校验商品
      if (this.orderItems.length === 0) {
        uni.showToast({
          title: '订单商品为空',
          icon: 'none'
        })
        return
      }
      
      // 校验起送金额
      if (!this.isMinAmountReached) {
        uni.showToast({
          title: `还差¥${this.remainingAmount}元起送`,
          icon: 'none',
          duration: 2000
        })
        return
      }
      
      this.submitting = true
      uni.showLoading({ title: '提交中...' })
      
      try {
        // 构建订单数据
        const orderData = {
          orderType: 1, // 1-零食购买，2-取快递，3-取外卖，4-代买
          addressId: this.selectedAddress.id,
          items: this.orderItems.map(item => ({
            productId: item.productId,
            quantity: item.quantity
          })),
          remark: this.remark || ''
        }
        
        const { createOrder } = require('@/api/order')
        const result = await createOrder(orderData)
        
        uni.hideLoading()
        
        // 如果是购物车结算，清空购物车中已选商品
        if (this.fromPage === 'cart') {
          this.clearCartSelectedItems()
        }
        
        // 跳转到支付页面（模拟支付）
        uni.redirectTo({
          url: `/pages/order/payment?orderId=${result.id}&orderNo=${result.orderNo}&amount=${this.actualAmount}`
        })
        
      } catch (error) {
        console.error('提交订单失败:', error)
        uni.hideLoading()
        uni.showToast({
          title: error.message || '提交失败',
          icon: 'none'
        })
      } finally {
        this.submitting = false
      }
    },
    
    clearCartSelectedItems() {
      let cart = uni.getStorageSync('cart') || []
      const selectedProductIds = this.orderItems.map(item => item.productId)
      
      // 过滤掉已购买的商品
      cart = cart.filter(item => !selectedProductIds.includes(item.productId))
      
      // 更新购物车
      uni.setStorageSync('cart', cart)
      const totalCount = cart.reduce((sum, item) => sum + item.quantity, 0)
      uni.setStorageSync('cartCount', totalCount)
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: #f5f7fa;
  padding-bottom: 180rpx;
}

/* 收货地址 */
.address-section {
  background: #fff;
  padding: 32rpx;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
  gap: 24rpx;
  position: relative;
  transition: all 0.3s;
  
  &.has-address {
    background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
    border-left: 4rpx solid #667eea;
  }
}

.address-content {
  flex: 1;
  
  .address-header {
    display: flex;
    gap: 16rpx;
    align-items: center;
    margin-bottom: 16rpx;
    flex-wrap: wrap;
    
    .receiver-name {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .receiver-phone {
      font-size: 28rpx;
      color: #666;
    }
    
    .selected-badge {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: #fff;
      font-size: 22rpx;
      padding: 6rpx 16rpx;
      border-radius: 8rpx;
      margin-left: auto;
    }
  }
  
  .address-detail {
    display: flex;
    gap: 12rpx;
    align-items: flex-start;
    
    .address-icon {
      font-size: 28rpx;
    }
    
    .address-text {
      flex: 1;
      font-size: 26rpx;
      color: #666;
      line-height: 1.6;
    }
  }
}

.address-empty {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 16rpx;
  
  .empty-icon {
    font-size: 40rpx;
  }
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
  }
}

.arrow-icon {
  font-size: 48rpx;
  color: #999;
}

/* 商品列表 */
.product-section,
.delivery-section,
.remark-section,
.fee-section {
  background: #fff;
  padding: 32rpx;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 24rpx;
}

.product-item {
  display: flex;
  gap: 20rpx;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.product-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 12rpx;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  font-size: 28rpx;
  color: #333;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.product-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-price {
  font-size: 28rpx;
  color: #ff4d4f;
  font-weight: bold;
}

.product-quantity {
  font-size: 26rpx;
  color: #999;
}

/* 配送方式 */
.delivery-item {
  display: flex;
  align-items: center;
  gap: 16rpx;
  
  .delivery-icon {
    font-size: 36rpx;
  }
  
  .delivery-text {
    flex: 1;
    font-size: 28rpx;
    color: #333;
  }
  
  .delivery-fee {
    font-size: 28rpx;
    color: #ff4d4f;
    font-weight: bold;
  }
}

/* 订单备注 */
.remark-input {
  width: 100%;
  min-height: 120rpx;
  font-size: 28rpx;
  color: #333;
  background: #f5f7fa;
  padding: 20rpx;
  border-radius: 12rpx;
}

/* 起送提示 */
.min-amount-tip {
  background: #fff;
  padding: 24rpx 32rpx;
  margin-bottom: 20rpx;
}

.tip-content {
  display: flex;
  align-items: center;
  gap: 16rpx;
  padding: 20rpx 24rpx;
  border-radius: 12rpx;
  background: linear-gradient(135deg, #fff5f5 0%, #ffe0e0 100%);
  
  &.reached {
    background: linear-gradient(135deg, #f0fff4 0%, #c6f6d5 100%);
  }
}

.tip-icon {
  font-size: 32rpx;
}

.tip-text {
  flex: 1;
  font-size: 26rpx;
  color: #666;
  line-height: 1.4;
}

/* 费用明细 */
.fee-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 0;
  
  &.total {
    padding-top: 24rpx;
    border-top: 1rpx solid #f0f0f0;
    margin-top: 16rpx;
  }
}

.fee-label {
  font-size: 28rpx;
  color: #666;
}

.fee-value {
  font-size: 28rpx;
  color: #333;
  
  &.highlight {
    font-size: 36rpx;
    color: #ff4d4f;
    font-weight: bold;
  }
}

/* 底部提交栏 */
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 24rpx;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-between;
  align-items: center;
  z-index: 100;
}

.bar-left {
  display: flex;
  align-items: baseline;
  gap: 4rpx;
}

.total-label {
  font-size: 24rpx;
  color: #666;
}

.total-symbol {
  font-size: 22rpx;
  color: #ff4d4f;
  font-weight: bold;
}

.total-value {
  font-size: 36rpx;
  color: #ff4d4f;
  font-weight: bold;
}

.btn-submit {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 24rpx 48rpx;
  border-radius: 40rpx;
  transition: all 0.3s;
  
  &.disabled {
    background: linear-gradient(135deg, #cbd5e0 0%, #a0aec0 100%);
    opacity: 0.6;
  }
  
  .btn-text {
    font-size: 28rpx;
    color: #fff;
    font-weight: bold;
  }
}
</style>
